/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: libevent1.c
> Author:cjy
> Mail: 
> Created Time: 2024年12月11日 星期三 11时55分25秒
***************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <event.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "./libevent/usr/include/event2/listener.h"

// 读取数据
void read_cb(struct bufferevent *bev, void *ctx) {
    int fd = *(int *)ctx;
    char buf[128] = {0};
    size_t ret = bufferevent_read(bev, buf, sizeof(buf));
    if (ret <= 0) {
        printf("bufferevent_read error or no data!\n");
        return;
    }
    printf("从 %d 中读取到数据: %s\n", fd, buf);
}

// 读取完数据触发事件
void event_cb(struct bufferevent *bev, short what, void *ctx) {
    int fd = *(int *)ctx;
    printf("异常发生 %x\n", what);

    if (what & BEV_EVENT_EOF) {
        printf("客户端 %d 下线\n", fd);
    } else {
        printf("未知错误\n");
    }

    free(ctx); // 释放分配的内存
    bufferevent_free(bev); // 释放 bufferevent
}

// 客户端连接回调
void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg) {
    printf("连接成功 %d\n", fd);

    struct event_base *base = arg;

    int *pfd = malloc(sizeof(int));
    if (!pfd) {
        perror("malloc error");
        return;
    }
    *pfd = fd;

    struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    if (!bev) {
        printf("bufferevent_socket_new error!\n");
        free(pfd);
        return;
    }

    bufferevent_setcb(bev, read_cb, NULL, event_cb, pfd);
    bufferevent_enable(bev, EV_READ);
}

// 主函数
int main(int argc, const char *argv[]) {
    struct event_base *base = event_base_new();
    if (!base) {
        printf("event_base_new error\n");
        exit(-1);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8000);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    struct evconnlistener *listener = evconnlistener_new_bind(
        base, listener_cb, base, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 10,
        (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (!listener) {
        printf("evconnlistener_new_bind error\n");
        event_base_free(base);
        exit(-1);
    }

    event_base_dispatch(base);

    evconnlistener_free(listener);
    event_base_free(base);

    return 0;
}

